package io.renren.utils;

import io.renren.entity.ColumnEntity;
import io.renren.entity.TableEntity;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 代码生成器 json 生成相对应的Entity工具类
 *
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2016年12月19日 下午11:40:24
 */
public class JsonGenUtils {
	
	
	/**
	 * 功能：判断字符串是否为日期格式
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isDate(String strDate) {
		int dateTimeLen = 19;
	    if ((strDate == null) || (strDate.length() != dateTimeLen)) {
	        return false;
	    }
	    DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    try {
	        Date date = formatter.parse(strDate);
	        return strDate.equals(formatter.format(date));
	    } catch (Exception e) {
	        return false;
	    }
	}

    public static List<String> getJsonFileTemplates() {
    	 List<String> templates = new ArrayList<String>();
    	 templates.add("template/json/JsonTemplate.java.vm");
    	 return templates;
    }
  

    /**
     * 列名转换成Java属性名
     */
    public static String columnToJava(String columnName) {
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 表名转换成Java类名
     */
    public static String tableToJava(String tableName, String tablePrefix) {
        if (StringUtils.isNotBlank(tablePrefix)) {
            tableName = tableName.replaceFirst(tablePrefix, "");
        }
        return columnToJava(tableName);
    }

    /**
     * 获取配置信息
     */
    public static Configuration getConfig() {
        try {
            return new PropertiesConfiguration("generator.properties");
        } catch (ConfigurationException e) {
            throw new RRException("获取配置文件失败，", e);
        }
    }

     
  
    public static String getSaveJsonFileName(String template, String packageName, String moduleName) {
    	String handleModuleName = StringUtils.capitalize(moduleName);
        String packagePath = "main" + File.separator + "java" + File.separator;
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator + moduleName + File.separator;
        }
    	if (template.contains("JsonTemplate.java.vm")) {
    		return packagePath + "dto" + File.separator + handleModuleName+"Info" + "DTO.java";
        } 
    	
    	return null;
    }
    
    
    public static List<String> handleParseJson(Map<String, Object> jsonMap,List<String> jsonKey) {
    	List<String> resultList=new ArrayList<>();
    	
		/*
		 * for (String tmp:jsonKey) { int i=0; String
		 * aweSome=jsonMap.get(tmp).toString(); i++; if(i==1) {
		 * 
		 * }
		 * 
		 * 
		 * }
		 */
    	
    	return resultList;
    	
    }
    
	public static void createJavaEntityFileFromJson(Map<String, Object> jsonMap,List<String> jsonKey, ZipOutputStream zip) {
		 // 配置信息
        Configuration config = getConfig();
     // 设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(prop);
        String mainPath = config.getString("mainPath");
        mainPath = StringUtils.isBlank(mainPath) ? "io.renren" : mainPath;
		 // 封装模板数据
        Map<String, Object> map = new HashMap<>();
        map.put("baseClassName", StringUtils.capitalize(config.getString("moduleName"))+"InfoDTO");
        map.put("mainPath", mainPath);
        map.put("package", config.getString("package"));
        map.put("moduleName", config.getString("moduleName"));
        map.put("modulename", config.getString("moduleName").toLowerCase());
        map.put("ModuleName", StringUtils.capitalize(config.getString("moduleName")));
        map.put("author", config.getString("author"));
        map.put("email", config.getString("email"));
        map.put("datetime", DateUtils.format(new Date(), DateUtils.DATE_TIME_PATTERN));
        map.put("isRootNode",false);
         
        
		List<Map<String, Object>> nodeList=new ArrayList<>(); 
		for (String tmp : jsonKey ){
			Map<String, Object> nodeMap = new HashMap<>();
			nodeMap.put("nodeName", tmp);
			String value=jsonMap.get(tmp).toString();
			if(value.startsWith("{")) {
				nodeMap.put("nodeClassName", StringUtils.capitalize(tmp));
			}else if(value.startsWith("[")) {
				if(value.startsWith("[{")){
					nodeMap.put("nodeClassName", "List<"+StringUtils.capitalize(tmp)+">");
				}else if(value.startsWith("[\"")) {
					nodeMap.put("nodeClassName", "List<String>");
				}else {
					nodeMap.put("nodeClassName", "List<String>");
				}
				
			}
			else if(value.startsWith("\"")){
				nodeMap.put("nodeClassName", "String");
			} /*
				 * else
				 * if(!value.startsWith("\"")&&StringUtils.isNumeric(value)&&!value.equals(""))
				 * { nodeMap.put("nodeClassName", "Double"); }
				 */
			else if(isDate(value)) {
				nodeMap.put("nodeClassName", "Date");
			}
			else {
				nodeMap.put("nodeClassName", "String");
			}
			
			
			nodeList.add(nodeMap); 
		}
		 
        
        map.put("nodeList",nodeList);
        VelocityContext context = new VelocityContext(map);

        // 获取模板列表
        List<String> templates = getJsonFileTemplates();
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);

            try {
                // 添加到zip
                String fileName = getSaveJsonFileName(template,config.getString("package"),
                        config.getString("moduleName"));
                zip.putNextEntry(new ZipEntry(fileName));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                throw new RRException("渲染模板失败" , e);
            }
        } 
		 
		
	}
    
}
